package com.wangyadong.hobby.schedule.jobtask.teststack;


import com.wangyadong.hobby.schedule.jobtask.tree.pq.Entry;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/9/2715:39
 **/
public class UnSortMapExample<K, V> extends AbstractMapExample<K, V> {
    private int CAPACITY = 1000;


    private int size = -1;
    private Entry<K, V>[] tables;

    public UnSortMapExample() {
//        table = new ArrayList(CAPACITY);
        tables = new Entry[CAPACITY];
    }

    public UnSortMapExample(int capa) {
//        table = new ArrayList(capa);
        tables = new Entry[capa];
    }

    @Override
    public int size() {
        return size + 1;
    }

    private int findIndex(K k) {
        if(null==tables){
            return  -1;
        }
        for (int i = 0; i < tables.length; i++) {

            Entry<K, V> entry = tables[i];
            if(entry!=null){
                if (entry.getKey().equals(k))
                    return i;
            }

        }
        return -1;
    }

    @Override
    public V get(K k) {
        int index = findIndex(k);
        if (-1 == index)
            return null;
        else
            return tables[index].getValue();
    }

    @Override
    public V put(K k, V v) {

        int index = findIndex(k);
        AbstractMap.MapEntry mapEntry = new AbstractMap.MapEntry();
        if (-1 == index) {
            mapEntry.setKey(k);
            mapEntry.setValue(v);
            tables[size+1]=mapEntry;
            size++;
            return v;
        } else {
            mapEntry = (AbstractMap.MapEntry) tables[index];
            mapEntry.setValue(v);
            return v;
        }
    }

    @Override
    public V remove(K k) {
        int index = findIndex(k);
        if (-1 == index) {
            return null;
        }
        Entry<K, V> table = tables[index];
        tables[index] = null;
        int length = tables.length;
        if (index != length - 1) {
            tables[index] = tables[length - 1];
        }
        size--;
        return table.getValue();
    }

    @Override
    public Iterable entrySet() {
        return null;
    }

    public static void main(String[] args) {
        UnSortMapExample unSortMapExample = new UnSortMapExample();
        unSortMapExample.put("1", "2");
        unSortMapExample.put("2", "3");
        unSortMapExample.put("3", "4");
        System.out.println(unSortMapExample.get("2"));
    }
}
